<!--
 * @Description  : 
 * @Autor        : guoxi
 * @Date         : 2022-08-11 15:43:50
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2022-10-14 10:32:55
 * @FilePath     : \rpms\src\views\project\create\components\Funds.vue
-->
<template>
  <el-button
    v-if="!isChange"
    @click="handleAdd"
    class="btnClass"
    type="primary"
    icon="el-icon-plus"
  />
  <TreeTable
    ref="treeTable"
    :value="model.treeTableData"
    :type="model.dataType"
  />
  <el-dialog
    title="导入预算"
    v-model="model.dialogFormVisible"
    destroy-on-close
    width="45vw"
  >
    <span style="color: red; font-size: 14px; position: relative; top: -20px"
      >请注意：填报金额单位为 元（人民币）。</span
    >
    <p style="margin-bottom: 15px">
      可点击下载模版：
      <el-link type="primary" @click="postXlsxDownload"
        >承担单位经费预算导入模版.xlsx
      </el-link>
    </p>
    <el-table :data="model.tableData" style="width: 100%" border>
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="name" label="承担单位" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="address" label="导入">
        <template #default="scope">
          <el-upload
            name="uploadFile"
            :accept="model.acceptTypes"
            :action="model.uploadComUrl"
            :headers="model.uploadHeaders"
            :on-success="
              (res, file, fileList) => {
                handleSuccess(res, file, fileList, scope.row);
              }
            "
            :on-remove="
              (file, fileList) => {
                handleRemove(file, fileLis, scope.row);
              }
            "
            :on-error="model.handleError"
            :file-list="scope.row.dFiles"
            :before-upload="model.beforeAvatarUpload"
            :on-preview="handlePreview"
          >
            <el-link size="small" type="primary">导入</el-link>
          </el-upload>
        </template>
      </el-table-column>
    </el-table>
    <br />
    <el-row justify="end">
      <el-button @click="model.dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </el-row>
  </el-dialog>
</template>

<script lang="ts">
import {
  reactive,
  defineComponent,
  onMounted,
  watch,
  nextTick,
  ref
} from "vue";
import NotifMessage from "/@/utils/message/notification";
import { useUpload } from "/@/hooks";
import TreeTable from "/@/components/treeTable/index.vue";
import { dataType } from "/@/components/treeTable/data";
import { getFundForProject, importFundForProject } from "/@/api/funds";
import { useRoute } from "vue-router";

export default defineComponent({
  name: "Funds",
  components: { TreeTable },
  props: {
    companyList: {
      type: Array,
      default: () => []
    }
  },
  emits: ["updateFiles"],

  //   emits: ["change", "load"],
  setup(props, { emit }) {
    const route = useRoute();
    const treeTable = ref(null);
    const isChange = route.query.mode === "change" ? true : false;
    const {
      handleError,
      beforeAvatarUpload,
      uploadComUrl,
      acceptTypes,
      uploadHeaders
    } = useUpload();
    // console.log(props, ctx);
    const model = reactive({
      dataType: dataType,
      tableData: [],
      treeTableData: [],
      dialogFormVisible: false,
      handleError,
      beforeAvatarUpload,
      uploadComUrl,
      acceptTypes,
      uploadHeaders,
      cloumns: []
    });
    const handleAdd = () => {
      if (model.tableData.length === 0) {
        NotifMessage.warning("请先添加承担单位！");
      } else {
        model.dialogFormVisible = true;
      }
    };

    const handleSubmit = async () => {
      const params = [];
      let deptFiles = {}; // 存放公司与其对应的预算附件 key: deptId, value: el.dFiles
      model.tableData.forEach(el => {
        deptFiles[el.code] = el.dFiles || [];
        if (el.dFiles && el.dFiles.length > 0) {
          params.push({
            deptId: el.code,
            deptName: el.deptName,
            fileUUid: el.dFiles[0].uuidFile
          });
        }
      });
      const res = await importFundForProject(params);
      if (res.code === 200) {
        model.treeTableData = res.data;
        treeTable.value.model.data = model.treeTableData || [];
        treeTable.value.getCloumn([]);
        emit("updateFiles", deptFiles);
        model.dialogFormVisible = false;
      }
    };

    const postXlsxDownload = () => {
      window.open(
        `${location.origin}${location.pathname}/承担单位经费预算导入模版.xlsx`
      );
    };

    const handleSuccess = (res, file, fileList, item) => {
      if (res.code === 200) {
        nextTick(() => {
          item["dFiles"] = [
            {
              name: file.response.data.fileName,
              fileName: file.response.data.fileName,
              uuidFile: file.response.data.uuidFile
            }
          ];
          // if (!item.files) {
          //   item.files = [];
          // }
          // item.files.push(res.data);
        });
      }
    };

    const handleRemove = (file, fileList, item) => {
      item.dFiles = fileList;
    };

    const handlePreview = (item: any) => {
      if (item.response) {
        window.open(
          `${location.origin}${location.pathname}#/online?uuidFile=${item?.response.data.uuidFile}&fileName=${item?.response.data.fileName}`
        );
      } else {
        window.open(
          `${location.origin}${location.pathname}#/online?uuidFile=${item.uuidFile}&fileName=${item.fileName}`
        );
      }
    };

    const getDetail = async () => {
      const { code, data } = await getFundForProject(route.query.id);
      if (code === 200) {
        model.treeTableData = data;
        treeTable.value.model.data = model.treeTableData || [];
        treeTable.value.getCloumn([]);
      }
    };

    onMounted(() => {
      model.tableData = props.companyList;
      if (route.query.id) {
        getDetail();
      }
    });

    watch(
      () => [props.companyList],
      ([v2]) => {
        model.tableData = v2 || [];
      },
      { immediate: false }
    );

    return {
      handleSuccess,
      handleRemove,
      handlePreview,
      model,
      isChange,
      treeTable,
      handleAdd,
      handleSubmit,
      postXlsxDownload
    };
  }
});
</script>

<style lang="scss" scoped>
.btnClass {
  margin-bottom: 10px;
}
</style>
